import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { Encrypt } from "../../utils/aes";
const state = {
  token: getToken(),
  name: '',//名字
  avatar: '',//头像
  introduction: '',//简介
  roles: [],//全部角色
  role: {},//当前角色
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  // 设置当前角色
  SET_ROLE: (state, roles) => {
    state.role = roles
  }
}

const actions = {
  // user login 用户登录 userInfo里面就是账号密码
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      // username.trim()把空格去掉  Encrypt加密
      login({ username: Encrypt(username.trim()), password: Encrypt(password) }).then(response => {
        const { data } = response
        // 设置token
        console.log(data, 'tttttttttttttt');
        commit('SET_TOKEN', data.accessToken)
        // 设置Cookies
        setToken(data.accessToken)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info  获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // 调用一个接口 
      getInfo(state.token).then(response => {
        const { data } = response
        console.log(data, "登录成功后");
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        // 角色
        let roles = data.roles
        const { username, portrait } = data.userInfo

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        commit('SET_ROLES', roles)
        commit('SET_ROLE', roles[0])
        commit('SET_NAME', username)
        commit('SET_AVATAR', portrait)
        commit('SET_INTRODUCTION', '')
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout退出登录
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resetRouter()

      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token 删除token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions 
  /**
   * 作用：改变角色
   * @param {*} param0 
   * @param {*} role 
   */
  async changeRoles({ commit, dispatch }, role) {


    // 重值路由 切换得时候把路由给清空 然后重新请求
    resetRouter()

    // generate accessible routes map based on roles 生成动态路由
    const accessRoutes = await dispatch('permission/generateRoutes', role, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
